package com.dapeis.api.controller.collocation.impl;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import com.ag.core.base.Pager;
import com.ag.core.exception.InvalidVerifyCodeException;
import com.ag.core.exception.SysTipsException;
import com.ag.core.utils.AgAssert;
import com.ag.dao.PagerHelper;
import com.ag.module.common.api.domain.SMS;
import com.ag.module.common.api.service.SMSService;
import com.ag.utils.NumberUtils;
import com.ag.utils.json.AGsonBuilder;
import com.dapeis.api.controller.RestController;
import com.dapeis.api.controller.collocation.IMoneyController;
import com.dapeis.core.convert.pager.MoneyLogPagerSearchConvertCriteria;
import com.dapeis.core.utils.DBConfigUtils;
import com.dapeis.core.utils.StylistConstants;
import com.dapeis.domain.Bank;
import com.dapeis.domain.Collocation;
import com.dapeis.domain.MoneyLog;
import com.dapeis.domain.MoneyStatistics;
import com.dapeis.exception.SMSSendFaildException;
import com.dapeis.exception.moneyLog.SysMoneyLogException;
import com.dapeis.service.BankService;
import com.dapeis.service.CollocationService;
import com.dapeis.service.MoneyLogService;
import com.dapeis.tx.sms.OutLayMoneyNoticeText;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

/**
 * @author 作者 E-mail: hzyuanyong@126.com
 * @version 创建时间：2017年5月24日 下午3:13:38 类说明
 */
@Controller
@RequestMapping("/dps/wallet")
public class MoneyController extends RestController implements IMoneyController {

    @Resource
    MoneyLogService moneyLogService;
    @Resource
    CollocationService collocationService;
    @Resource
    SMSService smsService;
    @Resource
    BankService bankService;

    @Override
    public JsonElement myAccout(
	    @RequestParam(required = false) Integer curretPager,
	    HttpServletRequest request) {
	MoneyStatistics ms = moneyLogService
		.getCollocationAllStatistics(getThreadLocalCollocationId());

	Pager pager = new Pager();
	pager.init(MoneyLog.class, new MoneyLogPagerSearchConvertCriteria());
	if (NumberUtils.isValid(curretPager)) {
	    pager.setCurrentPage(curretPager);
	}
	Example example = new Example(MoneyLog.class);
	Criteria criteria = example.createCriteria();
	criteria.andEqualTo(MoneyLog.PROPERTY_COLLOCATIONID,
		getThreadLocalCollocationId());
	example.orderBy(MoneyLog.PROPERTY_CREATETIME).desc();
	pager.setExample(example);
	moneyLogService.pager(pager);
	if (!(pager.getItemList().isEmpty())) {
	    PagerHelper.pager(pager, moneyLogService.getMoneyLogExtMapper());
	}
	JsonObject json = buildSuccess();
	json.add("data", AGsonBuilder.create().toJsonTree(ms));
	json.add("pager", AGsonBuilder.create().toJsonTree(pager));
	return json;
    }

    @Override
    public JsonElement withdrawal(@RequestParam String money, String code,
	    HttpServletRequest request) {
	if (!smsService.checkVerifyCode(
		StylistConstants.ChannelType.DPS.MONEY_OUTLAY,
		getThreadLocalCollocation().getContact(), code)) {
	    throw new InvalidVerifyCodeException();
	}
	try {
	    Float moneyFloat = new Float(money);
	    Float priceFooat = new Float(moneyFloat * 100);
	    Integer withdrawalMoney = priceFooat.intValue();
	    moneyLogService.enchashment(getThreadLocalCollocationId(),
		    withdrawalMoney);
	    smsService.setVerifyCodeVaild(
		    StylistConstants.ChannelType.DPS.MONEY_OUTLAY,
		    getThreadLocalCollocation().getContact());
	    JsonObject json = buildSuccess();
	    return json;
	} catch (Exception e) {
	    throw new SysMoneyLogException("金额参数非法!");
	}
    }

    @Override
    public JsonElement sendSMS(@RequestParam String money) {
	try {
	    Float moneyFloat = new Float(money);
	    Float priceFooat = new Float(moneyFloat * 100);
	    Integer withdrawalMoney = priceFooat.intValue();
	    Collocation collocation = getThreadLocalCollocation();
	    AgAssert.isTrue(!(collocation.getTotalMoney() < withdrawalMoney),
		    SysTipsException.class, "可用余额不足!");
	    // 测试时关闭
	    // AgAssert.isTrue(withdrawalMoney < 200*100,
	    // SysTipsException.class,"每次提现金额必须大于200");

	    Bank bank = bankService
		    .queryBankByCollocaitonId(getThreadLocalCollocationId());
	    JsonObject resultJson = new JsonObject();
	    JsonObject json = new JsonObject();
	    if (null != bank) {
		// 有银行卡信息时候,才发短信

		String verifyCode = String.valueOf(NumberUtils.random(4));
		OutLayMoneyNoticeText nt = new OutLayMoneyNoticeText(
			verifyCode, money);
		SMS unExpireationTimeSMS = smsService.getUnExpireationTimeSMS(
			StylistConstants.ChannelType.DPS.MONEY_OUTLAY,
			collocation.getContact());
		if (unExpireationTimeSMS != null) {// 如果有,
		    smsService.getDefaultSMSSendChannel().sendSMS(
			    collocation.getContact(),
			    unExpireationTimeSMS.getContent());
		} else {
		    boolean flag = smsService.sendSMS(
			    StylistConstants.ChannelType.DPS.MONEY_OUTLAY,
			    collocation.getContact(), verifyCode, nt.content());
		    if (!flag) {
			throw new SMSSendFaildException();
		    }
		}
		json.addProperty("succ", true);
		resultJson.addProperty("bankCard", bank.getBankCard());
		resultJson.addProperty("bankName",
			DBConfigUtils.getBankName(bank.getBankName()));
		// resultJson.addProperty("bankAddress",bank.getBankAddress());
		resultJson.addProperty("contact",
			subContact(collocation.getContact()));
		json.add("data", AGsonBuilder.create().toJsonTree(resultJson));
		json.addProperty("msg", "");
	    } else {
		json.addProperty("succ", false);
		json.addProperty("msg", "未绑定银行卡,请联系客服!");
		json.add("data", null);
	    }
	    return json;
	} catch (Exception e) {
	    throw new SysMoneyLogException("金额参数非法!");
	}
    }

    public String subContact(String contact) {
	String result = contact.substring(0, 3) + "****"
		+ contact.substring(contact.length() - 3, contact.length());
	return result;
    }

}
